class Section < ActiveRecord::Base
  require 'fixnum_overrides'
  has_and_belongs_to_many :students
  belongs_to :course
  belongs_to :instructor
  belongs_to :semester
  
  def time_span
    start_db = self.start_time.to_time
    end_db = self.end_time.to_time
    
    if start_db.hour.to_i > 12
      start_hour = start_db.hour.to_i - 12
      start_ap = 'pm'
    elsif start_db.hour.to_i == 12
      start_hour = start_db.hour.to_i
      start_ap = 'pm'
    else
      start_hour = start_db.hour.to_i
      start_ap = 'am'
    end
    
    if end_db.hour.to_i > 12
      end_hour = end_db.hour.to_i - 12
      end_ap = 'pm'
    elsif start_db.hour.to_i == 12
      end_hour = end_db.hour.to_i
      end_ap = 'pm'
    else
      end_hour = end_db.hour.to_i
      end_ap = 'am'
    end
    
    return "#{start_hour}:#{start_db.min.to_s_with_digits(2)} #{start_ap} - #{end_hour}:#{end_db.min.to_s_with_digits(2)} #{end_ap}"
  end
  
  def overlaps?(section)
    return false if self == section
    if (section.end_time < self.start_time) or (self.end_time < section.start_time)
      return false
    elsif (section.start_time == self.start_time) or (section.end_time == self.end_time)
      return true
    elsif (self.start_time < section.end_time) and (section.start_time < self.start_time)
      return true
    elsif (self.end_time < section.end_time) and (self.end_time > section.start_time)
      return true
    end
  end
  
  def overlap_any?
    registered_sections = Section.find(:all).select { |e| e.registered? }
    registered_sections.each do |sec|
      return sec if self.overlaps?(sec)
    end
    return false
  end
  
  def overlap_any_?
    s = rand(100)
    return false if s < 50
    
    return Course.with_number("MATH4317").sections.first
  end
  
end
